import tkinter
import tkinter.simpledialog
import tkinter.colorchooser
import tkinter.filedialog
# 需要执行 pip install pillow 安装扩展库
from PIL import ImageGrab  # 修正为正确的 PIL 导入方式

root = tkinter.Tk()
root.title('My Paint----by Dong Fuguo')  # 修正了引号不匹配的问题
root['width'] = 800
root['height'] = 600

# 控制是否允许画图的变量，1:允许，0:不允许
canDraw = tkinter.IntVar(value=0)
# 控制画图类型的变量，1:曲线，2:直线，3:矩形，4:文本，5:橡皮
what = tkinter.IntVar(value=1)
# 记录鼠标位置的变量
X = tkinter.IntVar(value=0)
Y = tkinter.IntVar(value=0)
# 前景色、背景色
foreColor = '#000000'  # 修正了颜色值的错误
backColor = '#FFFFFF'  # 修正了引号不匹配的问题

# 创建画布
canvas = tkinter.Canvas(root, bg='white', width=800, height=600)
# 修正了创建图片和创建图像对象的错误
# image = tkinter.PhotoImage()  # 不需要这个空图片对象
# canvas.create_image(800, 600, image=image)  # 也不需要这个

# 鼠标左键单击，允许画图，并记录当前鼠标位置
def onLeftButtonDown(event):
    canDraw.set(1)
    X.set(event.x)
    Y.set(event.y)
    if what.get() == 4:
        text = tkinter.simpledialog.askstring(title='Input text', prompt='Enter text:')
        if text:
            canvas.create_text(event.x, event.y, text=text, fill=foreColor)

canvas.bind("<Button-1>", onLeftButtonDown)  # 修正了绑定事件的语法错误

# 记录最后绘制图形的id
lastDraw = None

# 按住鼠标左键移动，画图
def onLeftButtonMove(event):
    global lastDraw
    if canDraw.get() == 0:
        return
    if what.get() == 1:
        # 使用当前选择的前景色绘制曲线
        canvas.create_line(X.get(), Y.get(), event.x, event.y, fill=foreColor, smooth=True)  # 添加了 smooth=True 使曲线更平滑（可选）
        X.set(event.x)
        Y.set(event.y)
    elif what.get() == 2:
        # 绘制直线，先删除刚刚画过的直线，再画一条新的直线
        try:
            canvas.delete(lastDraw)
        except Exception as e:
            pass
        lastDraw = canvas.create_line(X.get(), Y.get(), event.x, event.y, fill=foreColor)
    elif what.get() == 3:
        # 绘制矩形，先删除刚刚画过的矩形，再画一个新的矩形
        try:
            canvas.delete(lastDraw)
        except Exception as e:
            pass
        lastDraw = canvas.create_rectangle(X.get(), Y.get(), event.x, event.y, fill=backColor, outline=foreColor)
    elif what.get() == 5:
        # 橡皮，使用背景色填充10*10的矩形区域
        canvas.create_rectangle(event.x-5, event.y-5, event.x+5, event.y+5, outline=backColor, fill=backColor)

canvas.bind("<B1-Motion>", onLeftButtonMove)  # 修正了绑定事件的语法错误

# 鼠标左键抬起，不允许再画图了
def onLeftButtonUp(event):
    if what.get() == 2 or what.get() == 3:
        # 绘制直线或矩形（在抬起时确认）
        if lastDraw is not None:  # 确保 lastDraw 不是 None
            lastDraw = canvas.create_line(X.get(), Y.get(), event.x, event.y, fill=foreColor) if what.get() == 2 else \
                canvas.create_rectangle(X.get(), Y.get(), event.x, event.y, fill=backColor, outline=foreColor)
    canDraw.set(0)
    global lastDraw
    lastDraw = None  # 清除 lastDraw 以防止误删

canvas.bind('<ButtonRelease-1>', onLeftButtonUp)  # 修正了绑定事件的语法错误

# 创建菜单
menu = tkinter.Menu(root, tearoff=0)

# 打开图像文件
def open_image():
    filename = tkinter.filedialog.askopenfilename(title='Open Image', filetypes=[('Image Files', '*.jpg;*.png;*.gif')])
    if filename:
        try:
            image = tkinter.PhotoImage(file=filename)
            canvas.create_image(80, 80, image=image, anchor=tkinter.NW)  # 添加了 anchor 参数来定位图片
        except Exception as e:
            print("Failed to load image:", e)

menu.add_command(label='Open', command=open_image)  # 修正了添加菜单项的语法错误

# 保存绘制的图片
def save_image():
    left = int(root.winfo_rootx())
    top = int(root.winfo_rooty())
    width = root.winfo_width()
    height = root.winfo_height()
    im = ImageGrab.grab((left, top, left + width, top + height))
    filename = tkinter.filedialog.asksaveasfilename(title='Save Image', filetypes=[('PNG Image', '*.png')])
    if filename and not filename.endswith('.png'):
        filename += '.png'
    im.save(filename)

menu.add_command(label='Save', command=save_image)  # 修正了添加菜单项的语法错误

# 添加菜单，清除，遍历画布上的所有图像，逐个删除
def clear_canvas():
    for item in canvas.find_all():
        canvas.delete(item)

menu.add_command(label='Clear', command=clear_canvas)  # 修正了添加菜单项的语法错误

# 添加分割线
menu.add_separator()  # 修正了添加分割线的语法错误

# 创建子菜单，用来选择绘图类型
menuType = tkinter.Menu(menu, tearoff=0)

def draw_curve():
    what.set(1)

menuType.add_command(label='Curve', command=draw_curve)  # 修正了添加菜单项的语法错误

def draw_line():
    what.set(2)

menuType.add_command(label='Line', command=draw_line)  # 修正了添加菜单项的语法错误

def draw_rectangle():
    what.set(3)

menuType.add_command(label='Rectangle', command=draw_rectangle)  # 修正了添加菜单项的语法错误

def draw_text():
    text = tkinter.simpledialog.askstring(title='Input Text', prompt='Enter what you want to draw:')
    if text:
        what.set(4)

menuType.add_command(label='Text', command=draw_text)  # 修正了添加菜单项的语法错误

# 选择前景色
def choose_fore_color():
    global foreColor
    foreColor = tkinter.colorchooser.askcolor()[1]

menuType.add_command(label='Choose Foreground Color', command=choose_fore_color)  # 修正了添加菜单项的语法错误

# 选择背景色
def choose_back_color():
    global backColor
    backColor = tkinter.colorchooser.askcolor()[1]

menuType.add_command(label='Choose Background Color', command=choose_back_color)  # 修正了添加菜单项的语法错误

# 橡皮
def on_erase():
    what.set(5)

menuType.add_command(label='Erase', command=on_erase)  # 修正了添加菜单项的语法错误

menu.add_cascade(label='Type', menu=menuType)  # 修正了添加子菜单的语法错误

# 鼠标右键抬起，弹出菜单
def onRightButtonUp(event):
    menu.post(event.x_root, event.y_root)  # 修正了参数名称的错误

canvas.bind("<ButtonRelease-3>", onRightButtonUp)  # 修正了绑定事件的语法错误

canvas.pack(fill=tkinter.BOTH, expand=tkinter.YES)  # 修正了pack方法的参数错误

root.mainloop()